// HTTP请求工具
const BASE_URL = 'https://api.example.com'

// 请求拦截器
const requestInterceptor = (config) => {
	// 添加token
	const token = uni.getStorageSync('token')
	if (token) {
		config.header = config.header || {}
		config.header.Authorization = `Bearer ${token}`
	}
	
	// 添加公共参数
	config.header['Content-Type'] = 'application/json'
	
	// 显示加载状态
	if (config.showLoading !== false) {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
	}
	
	return config
}

// 响应拦截器
const responseInterceptor = (response) => {
	// 隐藏加载状态
	uni.hideLoading()
	
	const { data, statusCode } = response
	
	// HTTP状态码检查
	if (statusCode !== 200) {
		uni.showToast({
			title: `请求失败 ${statusCode}`,
			icon: 'none'
		})
		return Promise.reject(new Error(`HTTP ${statusCode}`))
	}
	
	// 业务状态码检查
	if (data.code !== 200) {
		uni.showToast({
			title: data.message || '请求失败',
			icon: 'none'
		})
		return Promise.reject(new Error(data.message || '请求失败'))
	}
	
	return data
}

// 错误处理
const errorHandler = (error) => {
	uni.hideLoading()
	
	console.error('请求错误:', error)
	
	// 网络错误
	if (error.errMsg && error.errMsg.includes('network')) {
		uni.showToast({
			title: '网络连接失败',
			icon: 'none'
		})
	} else if (error.errMsg && error.errMsg.includes('timeout')) {
		uni.showToast({
			title: '请求超时',
			icon: 'none'
		})
	} else {
		uni.showToast({
			title: error.message || '请求失败',
			icon: 'none'
		})
	}
	
	return Promise.reject(error)
}

// 封装请求方法
const request = (options) => {
	// 处理URL
	if (!options.url.startsWith('http')) {
		options.url = BASE_URL + options.url
	}
	
	// 应用请求拦截器
	const config = requestInterceptor(options)
	
	return new Promise((resolve, reject) => {
		uni.request({
			...config,
			success: (response) => {
				try {
					const result = responseInterceptor(response)
					resolve(result)
				} catch (error) {
					reject(error)
				}
			},
			fail: (error) => {
				errorHandler(error)
				reject(error)
			}
		})
	})
}

// GET请求
request.get = (url, params = {}, options = {}) => {
	return request({
		url,
		method: 'GET',
		data: params,
		...options
	})
}

// POST请求
request.post = (url, data = {}, options = {}) => {
	return request({
		url,
		method: 'POST',
		data,
		...options
	})
}

// PUT请求
request.put = (url, data = {}, options = {}) => {
	return request({
		url,
		method: 'PUT',
		data,
		...options
	})
}

// DELETE请求
request.delete = (url, params = {}, options = {}) => {
	return request({
		url,
		method: 'DELETE',
		data: params,
		...options
	})
}

// 上传文件
request.upload = (url, filePath, options = {}) => {
	const token = uni.getStorageSync('token')
	
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: BASE_URL + url,
			filePath,
			name: 'file',
			header: {
				Authorization: token ? `Bearer ${token}` : ''
			},
			...options,
			success: (response) => {
				try {
					const data = JSON.parse(response.data)
					if (data.code === 200) {
						resolve(data)
					} else {
						reject(new Error(data.message || '上传失败'))
					}
				} catch (error) {
					reject(new Error('响应解析失败'))
				}
			},
			fail: (error) => {
				errorHandler(error)
				reject(error)
			}
		})
	})
}

// 下载文件
request.download = (url, options = {}) => {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: BASE_URL + url,
			...options,
			success: (response) => {
				if (response.statusCode === 200) {
					resolve(response)
				} else {
					reject(new Error('下载失败'))
				}
			},
			fail: (error) => {
				errorHandler(error)
				reject(error)
			}
		})
	})
}

export default request
